package com.tuananh.radnom.service;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.listener.SimpleMessageListenerContainer;

import com.ajexperience.utils.DeepCopyException;
import com.ajexperience.utils.DeepCopyUtil;
import com.tuananh.radnom.model.NetInterface;
import com.tuananh.radnom.model.NetNode;
import com.tuananh.radnom.model.netpoller.Command;
import com.tuananh.radnom.model.netpoller.NetPoller;
import com.tuananh.radnom.model.netpoller.StringOutputStream;
import com.tuananh.radnom.model.protocol.netbios.ActiveNetBios;
import com.tuananh.radnom.persist.imp.xml.NetIntXmlDAO;
import com.tuananh.radnom.persist.imp.xml.NetNodeXmlDAO;
import com.tuananh.radnom.persist.imp.xml.NetPollerXmlDAO;
import com.tuananh.radnom.persist.imp.xml.XmlConfigHolder;
import com.tuananh.radnom.service.config.impl.DiscoverService;
import com.tuananh.radnom.service.config.impl.NetIntService;
import com.tuananh.radnom.service.config.impl.NetNodeService;
import com.tuananh.radnom.service.config.impl.PollService;
import com.tuananh.radnom.service.discovery.impl.ActiveDiscoverd;
import com.tuananh.radnom.service.discovery.impl.PassiveDiscoverd;
import com.tuananh.radnom.service.monitor.impl.PollDaemon;

import org.teleal.cling.UpnpService;
import org.teleal.cling.UpnpServiceImpl;
import org.teleal.cling.model.message.header.MXHeader;
import org.teleal.cling.model.message.header.STAllHeader;
import org.teleal.cling.model.meta.LocalDevice;
import org.teleal.cling.model.meta.RemoteDevice;
import org.teleal.cling.registry.Registry;
import org.teleal.cling.registry.RegistryListener;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import sun.net.ftp.*;
import sun.net.smtp.SmtpClient;
import sun.net.util.*;
import sun.net.www.protocol.http.HttpURLConnection;
/**
 * Unit test for simple App.
 */
public class AppTest1 extends TestCase {
	void upnp() {
		System.out.println("PassiveUpnp started");
		// TODO Auto-generated method stub
		// UPnP discovery is asynchronous, we need a callback
		RegistryListener listener = new RegistryListener() {

			public void remoteDeviceDiscoveryStarted(Registry registry,
					RemoteDevice device) {

			}

			public void remoteDeviceDiscoveryFailed(Registry registry,
					RemoteDevice device, Exception ex) {

			}

			public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
				//updateObservers(generate(device));
			}

			public void remoteDeviceUpdated(Registry registry,
					RemoteDevice device) {

			}

			public void remoteDeviceRemoved(Registry registry,
					RemoteDevice device) {

			}

			public void localDeviceAdded(Registry registry, LocalDevice device) {

			}

			public void localDeviceRemoved(Registry registry, LocalDevice device) {

			}

			public void beforeShutdown(Registry registry) {
				System.out
						.println("Before shutdown, the registry has devices: "
								+ registry.getDevices().size());
			}

			public void afterShutdown() {
				System.out.println("Shutdown of registry complete!");

			}
		};

		// This will create necessary network resources for UPnP right away
		System.out.println("Starting Cling...");
		UpnpService upnpService = new UpnpServiceImpl(listener);
		// Send a search message to all devices and services, they should
		// respond soon
		upnpService.getControlPoint().search(new STAllHeader(), 10);
	}

	/**
	 * Create the test case
	 * 
	 * @param testName
	 *            name of the test case
	 */
	public AppTest1(String testName) {
		super(testName);
	}

	/**
	 * @return the suite of tests being tested
	 */
	public static Test suite() {
		return new TestSuite(AppTest1.class);
	}

	/**
	 * Rigourous Test :-)
	 * 
	 * @throws DeepCopyException
	 * @throws InterruptedException
	 * @throws IOException
	 */
	public void testApp() throws DeepCopyException, InterruptedException {
		try {
			URL url = new URL("http://127.0.0.1:8081/");
			HttpURLConnection  urlConn = (HttpURLConnection) url.openConnection();
			urlConn.connect();
			SmtpClient client = new SmtpClient();
			
			String host = "127.0.0.1",
					user = "guest",
					password="12",
					sDir="";
			 try {
			      System.out.println("Connecting to host " + host);
			      FtpClient m_client = new FtpClient(host);
			      m_client.login(user, password);
			      System.out.println("User " + user + " login OK");
			      System.out.println(m_client.welcomeMsg);
			      m_client.cd(sDir);
			      System.out.println("Directory: " + sDir);
			      m_client.binary();
			      System.out.println("Success.");
			    } catch (Exception ex) {
			      System.out.println("Error: " + ex.toString());
			    }
//			upnp();
//			Thread.sleep(60000);
//			ApplicationContext context = new ClassPathXmlApplicationContext(
//					"spring-services.xml");
//			ActiveDiscoverd discoverd = new ActiveDiscoverd();
//			discoverd
//					.setDiscoverService(context.getBean(DiscoverService.class));
//			discoverd.setNetNodeService(context.getBean(NetNodeService.class));
//			discoverd.setNetIntService(context.getBean(NetIntService.class));
//			// Thread thread1 = new Thread(discoverd);
//			// thread1.start();
//			// while (!discoverd.isStop()) {
//			//
//			// }
//			// ///////////////////
//			System.out.println("Begin passive");
//			PassiveDiscoverd passiveD = new PassiveDiscoverd();
//			passiveD.setDiscoverService(context.getBean(DiscoverService.class));
//			passiveD.setNetNodeService(context.getBean(NetNodeService.class));
//			passiveD.setNetIntService(context.getBean(NetIntService.class));
			// Thread thread = new Thread(passiveD);
			// thread.start();
			// while (true) {

			// }
			// Command command = new Command();
			// command.setPrefix("java -jar");
			// command.setPath("../config/commands/ping_check.jar");
			// HashMap<String, String> params= new HashMap<String, String>();
			// params.put("command-options", "-h 127.0.0.1");
			// System.out.println(command.execute(params));
			//
		//	 PollDaemon pollDaemon = context.getBean(PollDaemon.class);
			// (new Thread(pollDaemon)).run();

			// PollService pollService = context.getBean(PollService.class);
			// pollService.removePollInfo(null, "localNic1");
			// NetNodeService nodeService =
			// context.getBean(NetNodeService.class);
			// System.out.println(nodeService.getAll().get(0).getName());

			// DefaultExecutor executor = new DefaultExecutor();
			// int[] exitValues = { 0, 1, 2, 3 };
			// executor.setExitValues(exitValues);
			// ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);
			// StringOutputStream op = new StringOutputStream(), err = new
			// StringOutputStream();
			//
			// PumpStreamHandler pump = new PumpStreamHandler(op, err);
			//
			// executor.setWatchdog(watchdog);
			// executor.setStreamHandler(pump);
			// CommandLine cmdLine =
			// CommandLine.parse("java -jar ../config/commands/ping_check.jar -h 127.0.0.1");
			// try {
			// System.out.println(executor.execute(cmdLine));
			// System.out.println(op.getString());
			// op.close();
			// err.close();
			// } catch (ExecuteException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// } catch (IOException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
